<template>
  <div class="personal-contract-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="合同编号">
          <el-input
            v-model="filterForm.contractNo"
            placeholder="请输入合同编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="客户姓名">
          <el-input
            v-model="filterForm.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="签约时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="合同状态">
          <el-select v-model="filterForm.status" placeholder="请选择合同状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已生效" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 个人业绩概览 -->
    <el-row :gutter="20" class="performance-row">
      <el-col :span="6">
        <el-card class="performance-card">
          <div class="performance-item">
            <div class="performance-icon total">
              <el-icon><Document /></el-icon>
            </div>
            <div class="performance-content">
              <div class="performance-value">{{ performanceData.totalContracts }}</div>
              <div class="performance-label">我的合同总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="performance-card">
          <div class="performance-item">
            <div class="performance-icon amount">
              <el-icon><Money /></el-icon>
            </div>
            <div class="performance-content">
              <div class="performance-value">{{ formatNumber(performanceData.totalAmount) }}</div>
              <div class="performance-label">合同总额(万元)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="performance-card">
          <div class="performance-item">
            <div class="performance-icon commission">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="performance-content">
              <div class="performance-value">{{ formatNumber(performanceData.totalCommission) }}</div>
              <div class="performance-label">佣金收入(万元)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="performance-card">
          <div class="performance-item">
            <div class="performance-icon month">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="performance-content">
              <div class="performance-value">{{ performanceData.monthContracts }}</div>
              <div class="performance-label">本月新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 合同表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>我的合同列表</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增合同
            </el-button>
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出合同
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="contractNo" label="合同编号" width="150" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="客户电话" width="130" />
        <el-table-column prop="propertyInfo" label="房产信息" width="200" show-overflow-tooltip />
        <el-table-column prop="contractAmount" label="合同金额(万元)" width="140" align="right">
          <template #default="{ row }">
            <span class="amount-text">{{ formatNumber(row.contractAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="我的佣金(万元)" width="140" align="right">
          <template #default="{ row }">
            <span class="commission-text">{{ formatNumber(row.commission) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="commissionRate" label="佣金比例" width="100" align="center">
          <template #default="{ row }">
            {{ (row.commissionRate * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="signDate" label="签约日期" width="120" />
        <el-table-column prop="status" label="合同状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="执行进度" width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :color="getProgressColor(row.progress)"
              :stroke-width="8"
              text-inside
            />
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="付款状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getPaymentStatusTag(row.paymentStatus)">
              {{ getPaymentStatusName(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nextPayDate" label="下次付款" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleEdit(row)"
              :disabled="row.status === 'completed' || row.status === 'cancelled'"
            >
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="timeline">进度跟踪</el-dropdown-item>
                  <el-dropdown-item command="payment">付款记录</el-dropdown-item>
                  <el-dropdown-item command="print">打印合同</el-dropdown-item>
                  <el-dropdown-item command="share">分享合同</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 合同详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="合同详情"
      width="80%"
      @close="handleDetailDialogClose"
    >
      <div v-if="currentContract" class="contract-detail">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="合同编号">{{ currentContract.contractNo }}</el-descriptions-item>
              <el-descriptions-item label="客户姓名">{{ currentContract.customerName }}</el-descriptions-item>
              <el-descriptions-item label="客户电话">{{ currentContract.customerPhone }}</el-descriptions-item>
              <el-descriptions-item label="房产信息">{{ currentContract.propertyInfo }}</el-descriptions-item>
              <el-descriptions-item label="合同金额">{{ formatNumber(currentContract.contractAmount) }}万元</el-descriptions-item>
              <el-descriptions-item label="我的佣金">{{ formatNumber(currentContract.commission) }}万元</el-descriptions-item>
              <el-descriptions-item label="佣金比例">{{ (currentContract.commissionRate * 100).toFixed(1) }}%</el-descriptions-item>
              <el-descriptions-item label="签约日期">{{ currentContract.signDate }}</el-descriptions-item>
              <el-descriptions-item label="合同状态">
                <el-tag :type="getStatusTag(currentContract.status)">
                  {{ getStatusName(currentContract.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="执行进度">
                <el-progress
                  :percentage="currentContract.progress"
                  :color="getProgressColor(currentContract.progress)"
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="付款记录" name="payment">
            <el-table :data="currentContract.paymentRecords" border>
              <el-table-column prop="paymentDate" label="付款日期" width="120" />
              <el-table-column prop="paymentAmount" label="付款金额(万元)" width="140" align="right">
                <template #default="{ row }">
                  {{ formatNumber(row.paymentAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="paymentMethod" label="付款方式" width="120" />
              <el-table-column prop="paymentStatus" label="付款状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getPaymentStatusTag(row.paymentStatus)">
                    {{ getPaymentStatusName(row.paymentStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="进度跟踪" name="timeline">
            <el-timeline>
              <el-timeline-item
                v-for="(item, index) in currentContract.timeline"
                :key="index"
                :timestamp="item.timestamp"
                :type="item.type"
              >
                <h4>{{ item.title }}</h4>
                <p>{{ item.content }}</p>
              </el-timeline-item>
            </el-timeline>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrint">打印合同</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  Document, 
  Money, 
  TrendCharts, 
  Calendar,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const activeTab = ref('basic')

// 筛选表单
const filterForm = reactive({
  contractNo: '',
  customerName: '',
  dateRange: [],
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 个人业绩数据
const performanceData = reactive({
  totalContracts: 0,
  totalAmount: 0,
  totalCommission: 0,
  monthContracts: 0
})

// 表格数据
const tableData = ref([])
const currentContract = ref(null)

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
}

const handleReset = () => {
  Object.assign(filterForm, {
    contractNo: '',
    customerName: '',
    dateRange: [],
    status: ''
  })
  handleFilter()
}

const handleAdd = () => {
  ElMessage.info('新增合同功能开发中')
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleView = (row: any) => {
  currentContract.value = row
  activeTab.value = 'basic'
  detailDialogVisible.value = true
}

const handleEdit = (row: any) => {
  ElMessage.info(`编辑合同 ${row.contractNo}`)
}

const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'timeline':
      currentContract.value = row
      activeTab.value = 'timeline'
      detailDialogVisible.value = true
      break
    case 'payment':
      currentContract.value = row
      activeTab.value = 'payment'
      detailDialogVisible.value = true
      break
    case 'print':
      ElMessage.info(`打印合同 ${row.contractNo}`)
      break
    case 'share':
      ElMessage.info(`分享合同 ${row.contractNo}`)
      break
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const handleDetailDialogClose = () => {
  currentContract.value = null
  activeTab.value = 'basic'
}

const handlePrint = () => {
  ElMessage.info('打印功能开发中')
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          contractNo: 'HT202401001',
          customerName: '张三',
          customerPhone: '13800138001',
          propertyInfo: '朝阳区某小区3室2厅',
          contractAmount: 350.5,
          commission: 10.5,
          commissionRate: 0.03,
          signDate: '2024-01-15',
          status: 'active',
          progress: 75,
          paymentStatus: 'partial',
          nextPayDate: '2024-02-15',
          paymentRecords: [
            {
              paymentDate: '2024-01-15',
              paymentAmount: 105.15,
              paymentMethod: '银行转账',
              paymentStatus: 'completed',
              remark: '首付款'
            },
            {
              paymentDate: '2024-02-15',
              paymentAmount: 175.25,
              paymentMethod: '银行转账',
              paymentStatus: 'pending',
              remark: '二期款'
            }
          ],
          timeline: [
            {
              timestamp: '2024-01-15 10:00',
              title: '合同签署',
              content: '客户张三签署购房合同',
              type: 'primary'
            },
            {
              timestamp: '2024-01-15 14:30',
              title: '首付款到账',
              content: '收到客户首付款105.15万元',
              type: 'success'
            },
            {
              timestamp: '2024-01-20 09:00',
              title: '贷款申请',
              content: '协助客户提交银行贷款申请',
              type: 'info'
            }
          ]
        },
        {
          contractNo: 'HT202401002',
          customerName: '王五',
          customerPhone: '13800138002',
          propertyInfo: '海淀区某公寓2室1厅',
          contractAmount: 280.0,
          commission: 8.4,
          commissionRate: 0.03,
          signDate: '2024-01-14',
          status: 'pending',
          progress: 25,
          paymentStatus: 'unpaid',
          nextPayDate: '2024-01-20',
          paymentRecords: [],
          timeline: [
            {
              timestamp: '2024-01-14 16:00',
              title: '合同草拟',
              content: '完成合同草拟，等待客户确认',
              type: 'warning'
            }
          ]
        }
      ]
      pagination.total = 45
      
      // 更新个人业绩数据
      Object.assign(performanceData, {
        totalContracts: 45,
        totalAmount: 1250.8,
        totalCommission: 37.5,
        monthContracts: 8
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

// 工具方法
const formatNumber = (num: number) => {
  return num?.toFixed(2) || '0.00'
}

const getRowClassName = ({ row }: { row: any }) => {
  if (row.status === 'completed') return 'success-row'
  if (row.status === 'cancelled') return 'danger-row'
  if (row.status === 'pending') return 'warning-row'
  return ''
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    draft: 'info',
    pending: 'warning',
    active: 'success',
    completed: 'primary',
    cancelled: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    draft: '草稿',
    pending: '待审核',
    active: '已生效',
    completed: '已完成',
    cancelled: '已取消'
  }
  return nameMap[status] || status
}

const getPaymentStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    unpaid: 'danger',
    partial: 'warning',
    completed: 'success',
    pending: 'info'
  }
  return tagMap[status] || 'info'
}

const getPaymentStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    unpaid: '未付款',
    partial: '部分付款',
    completed: '已付清',
    pending: '待确认'
  }
  return nameMap[status] || status
}

const getProgressColor = (progress: number) => {
  if (progress >= 80) return '#67c23a'
  if (progress >= 60) return '#e6a23c'
  if (progress >= 40) return '#f56c6c'
  return '#909399'
}

// 初始化数据
const initData = () => {
  getTableData()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.personal-contract-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .performance-row {
    margin-bottom: 20px;
    
    .performance-card {
      .performance-item {
        display: flex;
        align-items: center;
        
        .performance-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 20px;
          color: white;
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.amount {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.commission {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.month {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }
        
        .performance-content {
          .performance-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 3px;
          }
          
          .performance-label {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .amount-text {
      color: #67c23a;
      font-weight: bold;
    }
    
    .commission-text {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .contract-detail {
    .el-tabs {
      margin-top: 20px;
    }
  }
}

// 表格行样式
:deep(.success-row) {
  background-color: rgba(103, 194, 58, 0.1) !important;
}

:deep(.danger-row) {
  background-color: rgba(245, 108, 108, 0.1) !important;
}

:deep(.warning-row) {
  background-color: rgba(230, 162, 60, 0.1) !important;
}
</style>
